package dataset.eolo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

import common.network.URLInterface;
import common.wind.WindData;

import dataset.ElabData;

public class EoloData extends ElabData {

	private ArrayList<WindData> eoloWindDataArrayPerDay;
	private WindData lastRecord = null;
	
	public EoloData(URLInterface aURLInterface) {
		super(aURLInterface);
		eoloWindDataArrayPerDay = new ArrayList<WindData>();
	}

	private void fillArrayList() throws Exception {
		eoloWindDataArrayPerDay.clear();
		ArrayList<String> eoloContent = urlinterface.getContent();
		Iterator i = eoloContent.iterator();
		while (i.hasNext()) {
			String s = (String) i.next();
			WindData awd = new WindData();
			StringTokenizer st = new StringTokenizer(s);
			int conta = 0;
			String awindDate = "";
			while (st.hasMoreTokens()) {
				String ns = new String(st.nextToken());
				if (!ns.equals("nodi")) {
					conta++;
					if (conta == 1) {
						awindDate = ns;
					} else if (conta == 2) {
						awd.setWindDateTime(awindDate, ns);
					} else if (conta == 3) {
						awd.setSpeed(ns);
					} else if (conta == 4) {
						awd.setDirection(ns);
					} else if (conta == 5) {
						awd.setMaxspeed(ns);
					} else if (conta == 6) {
						awd.setAvgspeed(ns);
					}
				}
			}
			if (awd.isOK()) {
				eoloWindDataArrayPerDay.add(awd);
				setLastRecord(awd);
			}
		}
	}

	private void setLastRecord(WindData awd) {
		String aTrend="";
		if (lastRecord != null) {
			if (lastRecord.getAvgspeed().intValue() < awd.getAvgspeed()
					.intValue()) {
				aTrend = WindData.TREND_UP;
			} else if (lastRecord.getAvgspeed().intValue() > awd
					.getAvgspeed().intValue()) {
				aTrend = WindData.TREND_DOWN;
			} else {
				aTrend = WindData.TREND_STABLE;
			}
		}
		lastRecord = awd;
		lastRecord.setTrend(aTrend);
	}

	public ArrayList<WindData> getWindData() {
		return eoloWindDataArrayPerDay;
	}

	public void refreshWindData() throws Exception {
		fillArrayList();
	}

	public String getLastRecord() {
		return lastRecord.toString();
	}

}
